<?php

	include_once 'EsendexSendService.php';	

	set_time_limit(0);
	//include_once( "EsendexSendService.php" );
	$configPath ="";
	$isNotTest = false;
	if( $argc == 1 ){
		die("No Arguments!!!");
	}else if( $argc == 2){
		$configPath = $argv[1];
		echo "test mode...";
	}else{
		$configPath = $argv[1];
		$isTestStr = $argv[2];
		if( strcasecmp($isTestStr,"true") == 0 ){
			$isNotTest = true;
		}
	
	}
	//if( substr($configPath, -1) != "/" && substr($configPath, -1) != "\\" ){
	
	//}
	
	
	$ini_array = parse_ini_file("../config/config.ini");
	
	date_default_timezone_set($ini_array["default_timezone"]);
	
	$conn = @mysqli_connect($ini_array["host"], $ini_array["username"], $ini_array["password"], $ini_array["db_name"]) or die("cann't connect the mysql db");
	
	
	$getRemindMobileSql = "SELECT appointment_no, mobile, appointment_datetime,Clinic_address, Clinic_name, appointment.clinicNo  FROM appointment, patient, clinic WHERE patient.Patient_no = appointment.Patient_no AND type=2 AND sub_type=0 AND UNIX_TIMESTAMP(appointment_datetime) - UNIX_TIMESTAMP(NOW()) > 0 AND UNIX_TIMESTAMP(appointment_datetime) - UNIX_TIMESTAMP(NOW()) < 24*60*60 and appointment.clinicNo=clinic.Clinic_no order by appointment.clinicNo";
	$getRemindMobileResult = mysqli_query($conn, $getRemindMobileSql);
	
	$SMSUsername = $ini_array["SMSusername"];
	$SMSPassword = $ini_array["SMSpassword"];
	$SMSAccount = $ini_array["SMSaccount"];
	//$sendService = new EsendexSendService($SMSUsername, $SMSPassword, $SMSAccount);
	
	$recipient = "";
	$type = "text";
	
	
	$sendService = new EsendexSendService($SMSUsername, $SMSPassword, $SMSAccount);
	
	
	do{
		
		
		
		$updateStateSql = "update appointment set sub_type = 1 where ";
		$hasMobile = false;
		$content = "";
		$previewClinicNo = -1;
		$recipient = "";
		while( $row = mysqli_fetch_array($getRemindMobileResult) ){
			$mobile = $row["mobile"];
			$appointmentNo = $row["appointment_no"];
			$appointment_date = date("F d.Y", strtotime($row["appointment_datetime"]));
			$appointment_time = date("H:i:s",strtotime($row["appointment_datetime"]));
			$clinicAddress = $row["Clinic_address"];
			$clinicNo = $row["clinicNo"];
			$clinicName = $row["Clinic_name"];
				
			if( $clinicNo != $previewClinicNo ){
				if( $previewClinicNo != -1 ){
					fclose($fp);
				}
				$previewClinicNo = $clinicNo;
				if( file_exists($configPath.$clinicNo.".txt") ==false ||  filesize($configPath.$clinicNo.".txt") == 0 ){
					$fp = fopen($configPath."default.txt","r");
					$content = fread($fp, filesize($configPath."default.txt"));
				}else{
					$fp = fopen($configPath.$clinicNo.".txt", "r");
					$content = fread($fp, filesize($configPath.$clinicNo.".txt"));
				}
	
	
			}
				
				
			$body = str_replace("<time>", $appointment_time, $content);
			$body = str_replace("<date>", $appointment_date, $body);
			if( strcmp(trim($clinicAddress), "") == 0 ){
				$body = str_replace("<location>", $clinicName, $body);
			}else{
				$body = str_replace("<location>", $clinicAddress, $body);
			}
				
			//echo $body;
			$returnResult;
			if( $isNotTest == true ){
				$returnResult = $sendService->SendMessage($mobile, $body, $type, true);
			}else{
				$returnResult = $sendService->SendMessage($mobile, $body, $type, false);
			}
			//foreach( $returnResult as $key => $value ){
			//	echo "key=".$key." value=".$value."\r\n";
			//}
			if( strcmp($returnResult["Result"], "OK") == 0 ){
				echo "send to $mobile success! appointment NO.:$appointmentNo MessageID:".$returnResult["MessageIDs"]."\r\n";
				if( $hasMobile == false ){
					$hasMobile = true;
					$recipient .= $mobile."#".$appointmentNo."#".$returnResult["MessageIDs"];
				}else{
					$updateStateSql .= " or ";
					$recipient .= ",".$mobile."#".$appointmentNo."#".$returnResult["MessageIDs"];
				}
				
				$updateStateSql .= "appointment_no=".$appointmentNo;
			}else{
				echo "send to $mobile fail! appointment No.:$appointmentNo message:";
				if( isset($returnResult["Message"])){
					echo $returnResult["Message"];
				}
				echo "\r\n";
			}
				
		}
	
		if( $hasMobile == true ){
			$updateStateResult = mysqli_query($conn, $updateStateSql);
			mysqli_query($conn, "COMMIT");
			$fileResult = date("Y-m-d H:i:s  ")."mobile:".$recipient." ";
	
			if( !$updateStateResult ){
				$fileResult .= " update_status:false";
			}else{
				$fileResult .= " update_status:true";
			}
				
			$fileResult .= "\r\n";
			$fp = fopen("ScheduleOutput.txt", "a");
			fwrite($fp, $fileResult);
			fclose($fp);
		}
		echo "running....\r\n";
		sleep(30);
		$getRemindMobileResult = mysqli_query($conn, $getRemindMobileSql);
	}while(true);
?>
